package cn.edu.xmu.oomall.customer.dao;

import cn.edu.xmu.javaee.core.util.CloneFactory;
import cn.edu.xmu.javaee.core.exception.BusinessException;
import cn.edu.xmu.javaee.core.model.ReturnNo;
import cn.edu.xmu.javaee.core.model.dto.UserDto;
import cn.edu.xmu.oomall.customer.dao.bo.Customer;
import cn.edu.xmu.oomall.customer.mapper.CustomerPoMapper;
import cn.edu.xmu.oomall.customer.mapper.po.CustomerPo;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.stereotype.Repository;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Objects;
import java.util.Optional;

import static cn.edu.xmu.javaee.core.model.Constants.IDNOTEXIST;


@Slf4j
@Repository
@RefreshScope
@RequiredArgsConstructor
public class CustomerDao {

    private final static Logger logger = LoggerFactory.getLogger(CustomerDao.class);

    private final static String KEY = "R%d";

    private final CustomerPoMapper customerPoMapper;

    private Customer build(CustomerPo po) {
        Customer bo = CloneFactory.copy(new Customer(), po);
        bo.setCustomerDao(this);
        return bo;
    }

    public Customer getCustomerById(UserDto user) {
        Optional<CustomerPo> customerPo = customerPoMapper.findById(user.getId());
        Customer customer = CloneFactory.copy(new Customer(), customerPo.get());
        return customer;
    }

    public Customer findById(Long id) {
        logger.debug("findById: id = {}", id);
        assert (!Objects.isNull(id)) : "id can not be null";
        Optional<CustomerPo> po = customerPoMapper.findById(id);
        if (po.isPresent()) {
            logger.debug("findById: retrieve from database customer = {}", po.get());
            return this.build(po.get());
        } else {
            throw new BusinessException(ReturnNo.RESOURCE_ID_NOTEXIST, String.format(ReturnNo.RESOURCE_ID_NOTEXIST.getMessage(), "客户", id));
        }
    }

    public void save(Customer bo, UserDto user) {
        bo.setModifier(user);
        bo.setGmtModified(LocalDateTime.now());
        CustomerPo po = CloneFactory.copy(new CustomerPo(), bo);
        logger.debug("save: po = {}", po);
        CustomerPo updatePo = customerPoMapper.save(po);
        if (IDNOTEXIST.equals(updatePo.getId())) {
            throw new BusinessException(ReturnNo.RESOURCE_ID_NOTEXIST, String.format(ReturnNo.RESOURCE_ID_NOTEXIST.getMessage(), "客户", bo.getId()));
        }
    }

    public  List<CustomerPo> findByMobile(String mobile) {
        List<CustomerPo> po = customerPoMapper.findByMobile(mobile);
        logger.debug("findByMobile: mobile = {}", mobile);
        return po;
    }
}
